package com.czkt.config;

import com.czkt.pojo.SysRoleRight;
import com.czkt.pojo.vo.SysUserVo;
import com.czkt.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.crazycake.shiro.RedisManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义域   就相当于我们提供给shiro的数据源
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    SysUserService sysUserService;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("进入获取用户权限！");

        //获取当前已认证的用户
        SysUserVo sysUserVo = (SysUserVo) principalCollection.getPrimaryPrincipal();


        //获取用户拥有的权限
        List<SysRoleRight> roleRightList = sysUserService.getRightListByRoleId(sysUserVo.getUsrRoleId());

        List<String> stringList = new ArrayList<>();
        for (SysRoleRight sysRoleRight : roleRightList) {
            stringList.add(sysRoleRight.getRfRightCode());
        }
//        List<String> stringList=
//                roleRightList.stream().map(roleRight-> roleRight.getRfRightCode())
//                        .collect(Collectors.toList());


        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(stringList);
        return simpleAuthorizationInfo;
    }


//    @Autowired
//    StringRedisTemplate stringRedisTemplate;

    /**
     * 认证 逻辑代码
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String userName = (String) authenticationToken.getPrincipal();


        SysUserVo sysUser = sysUserService.login(userName);
        //用户不存在抛出异常
        if (sysUser == null) {

            throw new UnknownAccountException();
        }

        //账号被禁用抛出异常
        if (sysUser.getUsrFlag() == 0) {

            throw new LockedAccountException();
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                sysUser,//身份(根据用户名查询数据库获得的用户)
                sysUser.getUsrPassword(),//凭证(查询数据库获得的密码)
                ByteSource.Util.bytes("czkt"),
//                new ByteSourceSerializable("czkt"),
                getName()//Realm对象的名称
        );


        return info;
    }

    /**
     * 清除当前登录用户的权限缓存
     */
    public void clearMyCachedAuthorizationInfo() {
        //获取当前登录的用户
        PrincipalCollection temp = SecurityUtils.getSubject().getPrincipals();


        clearCachedAuthorizationInfo(temp);


    }

//    @Autowired
//    RedisTemplate redisTemplate;

    /**
     * 删除缓存中shiro的授权信息
     */
    public void clearAllCachedAuthorizationInfo() {
        if (this.isAuthorizationCachingEnabled()) {//权限缓存是否可用

             Cache<Object, AuthorizationInfo> cache = null;
             CacheManager cacheManager = this.getCacheManager();//获取缓存中间件
             if (cacheManager != null) {
                String cacheName = this.getAuthorizationCacheName();  //获得权限缓存名称
                cache = cacheManager.getCache(cacheName);  //获得权限缓存

            }
             if (cache != null) {
               cache.clear();  //清空所有缓存

            }
//            RedisManager cacheManager = (RedisManager) this.getCacheManager();//获取缓存中间件
//            redisTemplate.delete(cacheManager.keys(this.keySerializer.serialize(this.keyPrefix + "*")));



        }

    }


}
